/*
 * Copyright (c) 2009, Hamish Morgan. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the University of Sussex nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package locusts.common.vibro;

import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.nio.ByteBuffer;
import locusts.lib.geom.Shapes;

/**
 * Class to manage to quantisisation of of input entities to the small output
 * matrix for VT devices.
 * 
 * @author Hamish Morgan
 */
public class VTAccumulator implements Cloneable {

    public static final transient int MIN_VALUE = 0x00;
    public static final transient int MAX_VALUE = 0xFF;
    //
    private final int rows;
    private final int cols;
    private final int width;
    private final int height;
    private final Rectangle2D[][] rects;
    private final double[][] areas;
    private final ByteBuffer buf;

    public VTAccumulator(int rows, int cols, int width, int height) {
        this.rows = rows;
        this.cols = cols;
        this.width = width;
        this.height = height;

        final double recWidth = (double) width / cols;
        final double recHeight = (double) height / rows;
        buf = ByteBuffer.allocate(rows * cols);

        rects = new Rectangle2D[rows][cols];
        areas = new double[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                rects[i][j] = new Rectangle2D.Double(
                        j * recWidth, i * recHeight, recWidth, recHeight);
                areas[i][j] = Shapes.area(rects[i][j]);
            }
        }
    }

    protected VTAccumulator(VTAccumulator other) {
        this.rows = other.rows;
        this.cols = other.cols;
        this.width = other.width;
        this.height = other.height;
        buf = ByteBuffer.allocate(rows * cols);
        this.buf.put(other.buf);
        rects = other.rects;
        areas = other.areas;
    }

    public int getCols() {
        return cols;
    }

    public int getRows() {
        return rows;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public boolean isEmpty() {
        for (int i = 0; i < buf.limit(); i++)
            if (buf.get(i) != 0)
                return false;
        return true;
    }

    private void boundsCheck(final int row, final int col) {
        if (row < 0 || col < 0 || row >= rows || col >= cols) {
            throw new IndexOutOfBoundsException("The specificied index: " +
                    row + "," + col + ") is outside the bounds of accumulator" +
                    " array with dimensions " +
                    rows + "x" + cols + ".");
        }
    }

    public void set(int row, int col, int value) {
        boundsCheck(row, col);
        if (value < MIN_VALUE || value > MAX_VALUE) {
            throw new IllegalArgumentException("The value argument (" + value +
                    ") is outside of the expect range: " + MIN_VALUE + " to " +
                    MAX_VALUE);
        }
        buf.put((row * cols) + col, (byte) (0xff & value));
    }

    public int get(int row, int col) {
        boundsCheck(row, col);
        return 0xff & buf.get((row * cols) + col);
    }

    public ByteBuffer getBuffer() {
        return (ByteBuffer) buf.duplicate().rewind();
    }

    public void add(Area area) {

        // Changed to find max intersection
        double maxAddValue = 0;
        int maxRowIndex = -1;
        int maxColIndex = -1;

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (!area.intersects(rects[i][j]))
                    continue;

                final Area intersection = new Area(rects[i][j]);
                intersection.intersect(area);
                final double ratio = Shapes.area(intersection) / Shapes.area(
                        rects[i][j]);
                double addValue = (ratio * MAX_VALUE);


                if(maxAddValue < addValue) {
                    maxAddValue = addValue;
                    maxRowIndex = i;
                    maxColIndex = j;
                }
//
//
//                if (addValue < 1)
//                    addValue = 1;
//                int newVal = get(i, j) + addValue;
//                if (newVal > MAX_VALUE) newVal = MAX_VALUE;
//                set(i, j, newVal);
            }
        }


        if(maxAddValue != 0) {
            set(maxRowIndex, maxColIndex, MAX_VALUE);
        }
    }

    @Override
    public VTAccumulator clone() {
        return new VTAccumulator(this);
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (j != 0) sb.append(' ');
                sb.append(get(i, j));
            }
            sb.append("\n");
        }
        return sb.toString();
    }
}
